package com.gitee.ly;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
@EnableConfigurationProperties(LightRegistryProperties.class)
public class DiscoverAndLoadBalanceAutoConfiguration {

    @Bean
    @Primary
    @ConditionalOnMissingBean
    public ClientManage clientManage(LightRegistryProperties properties, BeanFactory beanFactory) throws UnknownHostException {
        //ServiceName默认值
        if (StringUtils.isEmpty(properties.getServiceName())) {
            properties.setServiceName(beanFactory.getBean(Environment.class).getProperty("spring.application.name"));
        }
        //ip默认值
        if (StringUtils.isEmpty(properties.getIp())) {
            properties.setIp(InetAddress.getLocalHost().getHostAddress());
        }
        //port默认值
        if (properties.getPort() <= 1) {
            properties.setPort(Integer.parseInt(beanFactory.getBean(Environment.class).getProperty("server.port")));
        }
        if (properties.isEnable()) {
            return new ClientManage(properties.getServerBaseUrl(),
                    properties.getServiceName(),
                    properties.getSchema(),
                    properties.getIp(),
                    properties.getPort(),
                    properties.getHeaderU());
        } else {
            return new ClientManage(properties.getServerBaseUrl(),
                    properties.getServiceName(),
                    properties.getSchema(),
                    properties.getIp(),
                    properties.getPort(),
                    properties.getHeaderU(),
                    true);
        }
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean
    public DiscoverAndLoadBalancer discoverAndLoadBalancer(ClientManage clientManage) {
        return new DefaultDiscoverAndLoadBalancer(clientManage);
    }
}
